
package com.xxmassdeveloper.mpchartexample;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.PhoneNumberUtils;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendForm;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.components.YAxis.AxisDependency;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.xxmassdeveloper.mpchartexample.sqlite.DatabaseAccessFactory;
import com.xxmassdeveloper.mpchartexample.sqlite.module.Weight;

import org.apache.commons.lang3.math.NumberUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class LineChartActivity extends BaseActivity implements OnChartValueSelectedListener, View.OnClickListener {

    Handler handler = new Handler();

    private TextView mMinWeight;

    private LineChart mChart;

    private CustomFAB mFab;

    private CustomFABDel mFabDel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_linechart);

        mMinWeight = (TextView) findViewById(R.id.min_weight);
        mChart = (LineChart) findViewById(R.id.chart1);
        mFab = (CustomFAB) findViewById(R.id.fab);
        mFabDel = (CustomFABDel) findViewById(R.id.fab_del);
        mChart.setOnChartValueSelectedListener(this);
        mFab.setOnClickListener(this);
        mFabDel.setOnClickListener(this);

        // no description text
        mChart.getDescription().setEnabled(false);

        // enable touch gestures
        mChart.setTouchEnabled(true);

        mChart.setDragDecelerationFrictionCoef(0.9f);

        // enable scaling and dragging
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);
        mChart.setDrawGridBackground(false);
        mChart.setHighlightPerDragEnabled(true);

        // if disabled, scaling can be done on x- and y-axis separately
        mChart.setPinchZoom(true);

        // set an alternative background color
        mChart.setBackgroundColor(Color.BLACK);

        // add data
        setData();

        //mChart.animateX(1000);

        // get the legend (only possible after setting data)
        Legend l = mChart.getLegend();

        // modify the legend ...
        l.setForm(LegendForm.LINE);
        l.setTypeface(mTfLight);
        l.setTextSize(11f);
        l.setTextColor(Color.WHITE);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
//        l.setYOffset(11f);

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setTypeface(mTfLight);
        leftAxis.setTextColor(ColorTemplate.getHoloBlue());
        leftAxis.setAxisMaximum(78f);
        leftAxis.setAxisMinimum(70f);
        leftAxis.setDrawGridLines(true);
        leftAxis.setGranularityEnabled(true);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            setData();
        }
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.fab) {
            final EditText editText = new EditText(this); // 创建输入框
            editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
            editText.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

            final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setView(editText);
            alertDialog.setTitle("设置今天的体重");
            alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    setData();
                                }
                            }, 500);
                        }
                    });
                }
            });
            //分别设置三个button
            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (NumberUtils.isNumber(editText.getText().toString())) {
                        if (Float.valueOf(editText.getText().toString()) > 90) {
                            Toast.makeText(LineChartActivity.this, "吃的那么胖了？", Toast.LENGTH_LONG).show();
                            return;
                        } else if (Float.valueOf(editText.getText().toString()) < 70) {
                            Toast.makeText(LineChartActivity.this, "减肥第一阶段成功了？？！！", Toast.LENGTH_LONG).show();
                            alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog) {
                                    handler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            doSendSMSTo("123456789", "我减肥第一阶段成功了!!!");
                                        }
                                    }, 3000);
                                }
                            });
                            return;
                        } else {
                            Toast.makeText(LineChartActivity.this, "录入当前数据", Toast.LENGTH_LONG).show();
                            recordWeight(editText);
                        }
                        dialog.dismiss();//关闭对话框
                    } else {
                        Toast.makeText(LineChartActivity.this, "输入数据格式错误", Toast.LENGTH_LONG).show();
                    }
                }
            });
            alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();//关闭对话框
                }
            });
            alertDialog.show();//显示对话框
        } else if (v.getId() == R.id.fab_del) {
            final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("确定删除最后一条记录");
            alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    setData();
                                }
                            }, 500);
                        }
                    });
                }
            });
            //分别设置三个button
            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    DatabaseAccessFactory.getInstance(LineChartActivity.this).weightAccessor().deleteLast();
                    dialog.dismiss();//关闭对话框
                }
            });
            alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();//关闭对话框
                }
            });
            alertDialog.show();//显示对话框
        }
    }


    /**
     * 调起系统发短信功能
     *
     * @param phoneNumber
     * @param message
     */
    public void doSendSMSTo(String phoneNumber, String message) {
        if (PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)) {
            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
            intent.putExtra("sms_body", message);
            startActivity(intent);
        }
    }

    private void recordWeight(EditText editText) {
        Date dt = new Date();
        SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
        String dataString = matter1.format(dt);
        String[] datas = dataString.split("-");
        Weight weight = new Weight();
        weight.setId(weight.hashCode());
        weight.setYear(datas[0]);
        weight.setMonth(datas[1]);
        weight.setDay(datas[2]);
        weight.setWeight(Float.valueOf(editText.getText().toString()));
        DatabaseAccessFactory.getInstance(LineChartActivity.this).weightAccessor().insert(weight);
    }

    private void setData() {

        ArrayList<Weight> weights = DatabaseAccessFactory.getInstance(this).weightAccessor().getWeights();

        if (weights.size() <= 0) {
            Toast.makeText(LineChartActivity.this, "当前无体重数据", Toast.LENGTH_LONG).show();
            mMinWeight.setVisibility(View.GONE);
            return;
        }

        float minWeight = weights.get(0).getWeight();

        ArrayList<Entry> yVals1 = new ArrayList<Entry>();

        for (int i = 0; i < weights.size(); i++) {
            float val = weights.get(i).getWeight();
            yVals1.add(new Entry(i, val));
            minWeight = minWeight < val ? minWeight : val;
        }
        mMinWeight.setText("最低体重：" + minWeight + "Kg");
        mMinWeight.setVisibility(View.VISIBLE);

        LineDataSet set1;

        if (mChart.getData() != null && mChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(yVals1, "体重变化图");

            set1.setAxisDependency(AxisDependency.LEFT);
            set1.setColor(ColorTemplate.getHoloBlue());
            set1.setCircleColor(Color.WHITE);
            set1.setLineWidth(2f);
            set1.setCircleRadius(3f);
            set1.setFillAlpha(65);
            set1.setFillColor(ColorTemplate.getHoloBlue());
            set1.setHighLightColor(Color.rgb(244, 117, 117));
            set1.setDrawCircleHole(false);
            set1.setDrawHorizontalHighlightIndicator(false);

            // create a data object with the datasets
            LineData data = new LineData(set1);
            data.setValueTextColor(Color.WHITE);
            data.setValueTextSize(8f);

            // set data
            mChart.setData(data);
        }
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        Log.i("Entry selected", e.toString());
        mChart.centerViewToAnimated(e.getX(), e.getY(), mChart.getData().getDataSetByIndex(h.getDataSetIndex()).getAxisDependency(), 500);
    }

    @Override
    public void onNothingSelected() {
        Log.i("Nothing selected", "Nothing selected.");
    }


}
